package com.netty.pro.netty.tcp;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;

/**
 * @author xuzn
 * @ClassName: TcpClientHandler
 * @ProjectName netty-pro
 * @date 2020/3/21/9:49
 */
public class TcpClientHandler extends SimpleChannelInboundHandler<ByteBuf> {
  @Override
  protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
    byte[] buffer = new byte[msg.readableBytes()];
    msg.readBytes(buffer);
    String message = new String(buffer, CharsetUtil.UTF_8);
    System.out.println("客户端接收消息:" + message);
  }

  @Override
  public void channelActive(ChannelHandlerContext ctx) throws Exception {
    // 发送数据
    for (int i = 0; i < 10; i++) {
      ctx.writeAndFlush(Unpooled.copiedBuffer("hello server~" + i, CharsetUtil.UTF_8));
    }
  }

  @Override
  public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
    cause.printStackTrace();
    ctx.close();
  }
}
